/**
 * @author:linjiye
 * @date: 2024/12/25
 * @desc:
 **/

import {StyleSheet, Text, TextInput, TouchableOpacity, View} from 'react-native'
import React, {useEffect, useRef, useState} from 'react'
import {useRouter} from "expo-router";
import PageScrollView from "@/components/PageScrollView";
import PageFormBtn from "@/components/PageFormBtn";
import UseExplosiveWrap from "@/components/useExplosive/UseExplosiveWrap";
import FcStep from "@/components/FcStep";
import FormTitle from "@/components/FormTitle";
import FcTextInput from "@/components/FcTextInput";
import ResolveResult from "@/components/explosiveFission/ResolveResult";
import FcButton from "@/components/FcButton";
import PageTabBar from "@/components/PageTabBar";
import PageTopBackBtn from "@/components/PageTopBackBtn";
import FissionResult from "@/components/explosiveFission/FissionResult";
import useApiOfSSE from "@/hooks/useApiOfSSE";
import {useDispatch, useSelector} from "react-redux";
import {set_params} from "@/store/reducer/explosiveFission/explosiveFissionSlice";
import {LinearGradient} from "expo-linear-gradient";
import FcModal from "@/components/FcModal";
import {useDownloadFromUrlMutation, useRecognizeMutation} from "@/store/api/aiInnovation/aiInnovationApi";
import useGetStorage from "@/hooks/useGetStorage";

type Props = {}

const index = (props: Props) => {
    const router = useRouter();
    const [pageScrollBodyH, setPageScrollBodyH] = useState(0)
    const [txt, setTxt] = useState('')
    const [fjText, setFjText] = useState('')
    const [isGetVideoLink, setIsGetVideoLink] = useState<boolean>(false)
    const [titleH, setTitleH] = useState(0)
    const [bottomH, setBottomH] = useState(0)
    const [step, setStep] = useState(1)
    const [source, setSource] = useState(null)
    const [aList, setAList] = useState([])
    const [bList, setBList] = useState([])
    const [cList, setCList] = useState([])
    const [colors,setColors] = useState(['rgba(51,77,176,1)', 'rgba(198,94,253,1)'])
    const [videoLink,setVideoLink] = useState('')

    const [downloadFromUrlFun] = useDownloadFromUrlMutation?.({
        url: videoLink
    })
    const [recognizeFun] = useRecognizeMutation?.()

    const [params,setParams] = useState({})

    const dispatch = useDispatch()
    let p = useSelector(state => state.explosiveFission.params)
    useEffect(() => {
        if(p) setParams(p)
    },[p])

    const handlePageFormBtnClick = (val) => {
        getData()
        setStep(2)
    }

    const getData = async () => {
        // let sourceResult = useApiOfSSE({
        //     url: 'mm/aicreation/copy_splitting',
        //     payload: {
        //         text: txt,
        //     }
        // })
        //
        // setSource(sourceResult)
        //
        // sourceResult.addEventListener('message', (e) => {
        //
        //     let res = JSON.parse(e.data)
        //     if (res.status == 'success') {
        //         let text = res.text.replace(/(<br\/>)|(<br)/g, '');
        //         setFjText(text)
        //
        //         let startIndex1 = text.indexOf("【开头】") + "【开头】".length;
        //         let endIndex1 = text.indexOf("【中间】");
        //         let startIndex2 = text.indexOf("【中间】") + "【中间】".length;
        //         let endIndex2 = text.indexOf("【结尾】");
        //         let startIndex3 = text.indexOf("【结尾】") + "【结尾】".length;
        //
        //         let var1 = text.substring(startIndex1, endIndex1).trim();
        //         let var2 = text.substring(startIndex2, endIndex2).trim();
        //         let var3 = text.substring(startIndex3).trim();
        //
        //         // setAText(var1)
        //         // setBText(var2)
        //         // setCText(var3)
        //
        //         dispatch(set_params({
        //             ...params,
        //             aText: var1,
        //             bText: var2,
        //             cText: var3,
        //         }))
        //
        //     } else {
        //         sourceResult.close();
        //     }
        // })


        await useGetStorage('token').then(async (token) => {
            try {
                const response = await fetch(`${process.env.EXPO_PUBLIC_API_URL}mm/aicreation/copy_splitting`,{
                    method: 'POST',
                    headers: {
                        'content-type': 'application/json',
                        'x-access-token': token,
                    },
                    body: JSON.stringify({
                        text: txt,
                    })
                });
                console.log(response,'---');
                const blob = await response.blob();
                const reader = new FileReader();

                reader.onload = (event) => {
                    const result = event.target.result;
                    // 按行分割流式数据
                    const lines = result.split('\n');
                    lines.forEach((line) => {
                        if (line) {
                            console.log(line);
                            let newLine = `${line.replace('data:','')}`;
                            // 在这里处理流式数据
                            let res = JSON.parse(newLine)
                            if (res.status == 'success') {
                                let text = res.text.replace(/(<br\/>)|(<br)/g, '');
                                setFjText(text)

                                let startIndex1 = text.indexOf("【开头】") + "【开头】".length;
                                let endIndex1 = text.indexOf("【中间】");
                                let startIndex2 = text.indexOf("【中间】") + "【中间】".length;
                                let endIndex2 = text.indexOf("【结尾】");
                                let startIndex3 = text.indexOf("【结尾】") + "【结尾】".length;

                                let var1 = text.substring(startIndex1, endIndex1).trim();
                                let var2 = text.substring(startIndex2, endIndex2).trim();
                                let var3 = text.substring(startIndex3).trim();

                                // setAText(var1)
                                // setBText(var2)
                                // setCText(var3)

                                dispatch(set_params({
                                    ...params,
                                    aText: var1,
                                    bText: var2,
                                    cText: var3,
                                }))
                            }
                        }
                    });
                };

                reader.onerror = (error) => {
                    console.error('Error reading blob:', error);
                };

                reader.readAsText(blob);
            } catch (error) {
                console.log('Error fetching stream:', error);
            }
        })

    }

    const getScrollBodyInfo = ({height}) => {
        setPageScrollBodyH(height)
    }

    const handleText = (val) => {
        setTxt(val)
    }

    const getVideoLink = async () => {
        // 调用相机或者相册选择视频
        // const { uri } = await Video.launchCamera({ mediaType: 'video' });
        // console.log(uri);
    }

    const getTitleInfo = (event: any) => {
        const {height} = event.nativeEvent.layout;
        setTitleH(height)
    }

    const getBottomInfo = (event: any) => {
        const {height} = event.nativeEvent.layout;
        setBottomH(height)
    }

    function handleReExplosive() {
        setFjText('')
        getData()
    }

    function handleReFission() {
        dispatch(set_params({
            ...params,
            aIndex: 0,
            bIndex: 0,
            cIndex: 0,
            aList: [],
            bList: [],
            cList: [],
        }))
        getFissionData(params.articlesNum, params.aText, 'aList')
        getFissionData(params.articlesNum, params.bText, 'bList')
        getFissionData(params.articlesNum, params.cText, 'cList')
    }

    function handleAssembly(){
        // router.navigate('/explosiveFission/result')
        router.navigate(`/aiOriginality/result?fromWay=explosiveFissionPage`)
    }

    function handleFission(){
        setStep(3)

        dispatch(set_params({
            ...params,
            aIndex: 0,
            bIndex: 0,
            cIndex: 0,
            aList: [],
            bList: [],
            cList: [],
        }))

        getFissionData(params.articlesNum, params.aText, 'aList')
        getFissionData(params.articlesNum, params.bText, 'bList')
        getFissionData(params.articlesNum, params.cText, 'cList')
    }
    
    async function getFissionData(num, text, type) {
       // let source = useApiOfSSE({
       //      url: 'mm/aicreation/copy_fission',
       //      payload: {
       //          num,
       //          text,
       //      }
       //  })
       //
       //  source.addEventListener('message', (e) => {
       //
       //      let res = JSON.parse(e.data)
       //      if (res.status == 'success') {
       //          let text = res.text.replace(/(<br\/>)|(<br)/g, '');
       //
       //          // console.log(text);
       //
       //          let list = text.split('||')
       //          switch (type) {
       //              case 'aList':
       //                  setAList(list)
       //                  break;
       //              case 'bList':
       //                  setBList(list)
       //                  break;
       //              case 'cList':
       //                  setCList(list)
       //                  break;
       //          }
       //
       //          dispatch(set_params({
       //              ...params,
       //              aList: aList,
       //              bList: bList,
       //              cList: cList,
       //          }))
       //
       //      } else {
       //          source.close();
       //      }
       //  })

        await useGetStorage('token').then(async (token) => {
            try {
                const response = await fetch(`${process.env.EXPO_PUBLIC_API_URL}mm/aicreation/copy_fission`,{
                    method: 'POST',
                    headers: {
                        'content-type': 'application/json',
                        'x-access-token': token,
                    },
                    body: JSON.stringify({
                        num,
                        text,
                    })
                });
                console.log(response,'---');
                const blob = await response.blob();
                const reader = new FileReader();

                reader.onload = (event) => {
                    const result = event.target.result;
                    // 按行分割流式数据
                    const lines = result.split('\n');
                    lines.forEach((line) => {
                        if (line) {
                            console.log(line);
                            let newLine = `${line.replace('data:','')}`;
                            // 在这里处理流式数据
                            let res = JSON.parse(newLine)
                            if (res.status == 'success') {
                                let text = res.text.replace(/(<br\/>)|(<br)/g, '');
                                let list = text.split('||')
                                switch (type) {
                                    case 'aList':
                                        setAList(list)
                                        break;
                                    case 'bList':
                                        setBList(list)
                                        break;
                                    case 'cList':
                                        setCList(list)
                                        break;
                                }

                                dispatch(set_params({
                                    ...params,
                                    aList: aList,
                                    bList: bList,
                                    cList: cList,
                                }))
                            }
                        }
                    });
                };

                reader.onerror = (error) => {
                    console.error('Error reading blob:', error);
                };

                reader.readAsText(blob);
            } catch (error) {
                console.log('Error fetching stream:', error);
            }
        })

    }

    const focusTextInput = () => {
        setColors(['rgba(51,77,176,1)', 'rgba(198,94,253,1)'])
    }
    const blurTextInput = () => {
        setColors(['white', 'white'])
    }

    const handleVideoLink = () => {
        downloadFromUrlFun({
            url: videoLink,
        }).then(res => {
            if(res?.data?.code === 200) {
                let file = res.data?.result || ''
                recognizeFun({
                    file: file.replace('\\','%5c')
                }).then(r => {
                    let d = r?.error?.data
                    let s = d?.split('","status":"success"}')[0]?.replace('data:{"text":"','')
                    setTxt(s)
                    setIsGetVideoLink(false)
                })
            }
        })
    }

    return (
        <PageScrollView
            getPageScrollBodyInfo={getScrollBodyInfo}
            isHaveHeader
            isTransparentTab
            pageTab={
                <PageTabBar
                    style={{marginVertical: 10}}
                    title={step===1?'爆文裂变':step===2?'文案分解结果':'裂变结果'}
                    left={
                        <View style={{flexDirection: 'row',alignItems: 'center'}}>
                            <PageTopBackBtn/>
                            {step>1 &&
                                <TouchableOpacity onPress={() =>
                                    // setStep(step-1)
                                    setStep(1)
                                } style={{marginLeft: 4}}>
                                    <Text style={{ fontFamily: 'FcIconFont',fontSize: 24,color: 'rgba(0,0,0,0.9)' }}>&#xe66a;</Text>
                                </TouchableOpacity>
                            }
                        </View>
                    }
                />
            }
            pageHeader={
                <FcStep step={step}/>
            }
            pageBottom={
                <View>
                    {step === 1 &&
                        <PageFormBtn btnName='分解文案' disable={txt == ''}
                                     onPageFormBtnClick={handlePageFormBtnClick}/>}
                    {step > 1 &&
                        <View>
                            <View style={styles.bottom_btn}>
                                <View style={{flex: 1, marginRight: 4}}>
                                    <FcButton
                                        onClick={() => step === 2 ? handleReExplosive() : handleReFission()}
                                        type='default'
                                        style={{
                                            width: '100%',
                                            height: 40,
                                            justifyContent: 'center',
                                            backgroundColor: '#F1F2F4',
                                            borderRadius: 8
                                        }}
                                        itemStyle={{fontSize: 15}}
                                        textName={step===2?'重新分解':'重新裂变'}/>
                                </View>
                                <View style={{flex: 1, marginLeft: 4}}>
                                    <FcButton
                                        onClick={() => step===2 ? handleFission() : handleAssembly()}
                                        type='BjJB'
                                        colors={['#6989FF', '#C65EFD']}
                                        style={{width: '100%', height: 40, justifyContent: 'center'}}
                                        itemStyle={{borderRadius: 8, fontSize: 15}}
                                        textName={step===2?'裂变':'混搭组合'}/>
                                </View>
                            </View>
                        </View>
                    }
                </View>
            }
        >
            {step === 1 &&
                <View style={[styles.resolve_wrap, {height: pageScrollBodyH - 16}]}>
                    <View onLayout={getTitleInfo}><FormTitle style={{paddingHorizontal: 16}} isLeftIcon
                                                             title='输入爆文原文'/></View>
                    <FcTextInput style={{marginHorizontal: 16}} multiline text={txt}
                                 placeholder={'输入/粘贴你的视频文案'} onChangeText={handleText}
                                 height={pageScrollBodyH - 16 - titleH - bottomH}/>
                    <View onLayout={getBottomInfo} style={styles.video_btn_wrap}>
                        <TouchableOpacity style={styles.video_btn} onPress={() => setIsGetVideoLink(true)}>
                            <Text style={styles.video_icon}>&#xe601;</Text>
                            <Text style={styles.video_txt}>视频链接获取</Text>
                        </TouchableOpacity>
                        <TouchableOpacity style={styles.video_btn} onPress={() => getVideoLink()}>
                            <Text style={styles.video_icon}>&#xe61b;</Text>
                            <Text style={styles.video_txt}>视频获取</Text>
                        </TouchableOpacity>
                    </View>
                </View>
            }
            {step === 2 && <ResolveResult />}
            {step === 3 && <FissionResult />}

            <FcModal
                isOpen={isGetVideoLink}
                onFcModalClose={() => setIsGetVideoLink(false)}
                titleText='视频链接获取'
            >
                <View>
                    <LinearGradient
                        colors={colors} // 渐变色
                        start={{x: 0, y: 0}}
                        end={{x: 1, y: 1}}
                        style={styles.gradient}
                    >
                        <TextInput
                            style={styles.video_link}
                            multiline={true}
                            // numberOfLines={4}
                            value={videoLink}
                            placeholderTextColor={'rgba(0, 0, 0, 0.3)'}
                            placeholder={'粘贴短视频网址即可提取文案 '}
                            underlineColorAndroid="transparent" // 设置安卓下的下划线颜色为透明
                            selectionColor="transparent" // 设置选中时的颜色为透明
                            onFocus={focusTextInput}
                            onBlur={blurTextInput}
                            onChangeText={setVideoLink}
                        />
                        {videoLink &&
                            <TouchableOpacity style={styles.close} onPress={() => setVideoLink('')}>
                                <Text style={{fontFamily: 'FcIconFont', fontSize: 12, color: 'white'}}>&#xe61a;</Text>
                            </TouchableOpacity>
                        }
                    </LinearGradient>

                    <View style={{
                        flexDirection: 'column',
                        alignItems: 'center',
                        justifyContent: 'center',
                        paddingBottom: 24
                    }}>
                        <FcButton
                            onClick={() => handleVideoLink()}
                            type='BjJB'
                            colors={videoLink? ['#6989FF', '#C65EFD']: ['rgba(105,137,255,0.4)','rgba(198,94,253,0.4)']}
                            style={{width: 168, height: 40, justifyContent: 'center'}}
                            itemStyle={{borderRadius: 8}}
                            textName='开始提取'></FcButton>
                    </View>
                </View>
            </FcModal>
        </PageScrollView>
    )
}

export default index

const styles = StyleSheet.create({
    resolve_wrap: {
        height: '100%',
        backgroundColor: 'white',
        flexDirection: 'column',
        justifyContent: "space-between",
        borderRadius: 8,
        paddingBottom: 0
    },

    video_btn_wrap: {
        flexDirection: "row",
        alignItems: "center",
        paddingHorizontal: 16,
        paddingVertical: 12,
        borderBottomWidth: 0.5,
        borderBottomColor: 'rgba(0, 0, 0, 0.1)',

    },
    video_btn: {
        flexDirection: 'row',
        alignItems: "center",
        backgroundColor: '#F1F2F4',
        paddingHorizontal: 8,
        paddingVertical: 4,
        borderRadius: 8,
        marginRight: 6,
    },
    video_icon: {
        fontFamily: 'FcIconFont',
        color: 'rgba(0, 0, 0, 0.9)',
        fontSize: 12,
    },
    video_txt: {
        color: 'rgba(0, 0, 0, 0.9)',
        fontSize: 12,
        marginLeft: 2
    },
    bottom_btn: {
        flexDirection: "row",
        alignItems: "center",
        paddingHorizontal: 16,
        height: 56,
        justifyContent: "space-between",
        backgroundColor: 'white'
    },

    btn_wrap: {
        flexDirection: "row",
        alignItems: "center",
        padding: 12,
        backgroundColor: 'white',
        marginBottom: 8,
        borderTopWidth: 0.5,
        borderTopColor: 'rgba(0, 0, 0, 0.1)',
    },
    btn: {
        flexDirection: "row",
        alignItems: "center",
        backgroundColor: '#F1F2F4',
        borderRadius: 8,
        paddingHorizontal: 8,
        height: 28,
        marginRight: 8
    },

    gradient: {
        // flex: 1,
        height: 82,
        margin: 16,
        borderRadius: 9,
        overflow: "hidden",
        alignItems: "center",
        justifyContent: "center",
        paddingHorizontal: 1,
        position: "relative"
    },
    video_link: {
        width: '100%',
        paddingHorizontal: 12,
        height: 80,
        borderRadius: 9,
        overflow: "hidden",
        flexDirection: "row",
        alignItems: "center",
        marginHorizontal: 37,
        backgroundColor: '#F1F2F4',
        color: 'rgba(0,0,0,0.9)',
        fontSize: 17,
        lineHeight: 26,
        paddingVertical: 8,
        borderWidth: 0, // 去掉边框
        outlineWidth: 0, // 去掉轮廓
        shadowOpacity: 0, // 去掉阴影
    },
    close: {
        width: 16,
        height: 16,
        borderRadius: 30,
        backgroundColor: 'black',
        justifyContent: "center",
        alignItems: "center",
        position: "absolute",
        right: 10,
        top: 10,
        zIndex: 100
    }
})